package fr.machizaud.research.handlers;

import fr.machizaud.research.FCPGenerator;
import fr.machizaud.research.MalformedDocumentException;
import fr.machizaud.research.XMLHandler;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.logging.Level;

/**
 * User: Andréa
 * Date: 23/01/11
 * Time: 18:11
 * <p/>
 * Check if given document respect FCP format
 */
public class FCPXMLChecker
        implements XMLHandler {
    private static final java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger(FCPXMLChecker.class.getCanonicalName());

    private FCPXMLChecker() {
    }

    private static class FCPXMLCheckerHolder {
        private static final FCPXMLChecker instance = new FCPXMLChecker();
    }

    public static FCPXMLChecker getInstance() {
        return FCPXMLCheckerHolder.instance;
    }

    @Override
    public void process(Document dom) throws MalformedDocumentException {
        logger.log(Level.INFO, "Handler {0}", getClass().getName());
        //Set some stuff for document builder
        SAXBuilder builder = new SAXBuilder(true);
        builder.setProperty(
                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema"
        );
        builder.setProperty(
                "http://java.sun.com/xml/jaxp/properties/schemaSource",
                new File(
                        FCPGenerator.XSD_PATH
                )
        );

        //put document into a buffer
        XMLOutputter outputter = new XMLOutputter();

        String rawOutput = outputter.outputString(dom);

        Reader domReader = new StringReader(
                rawOutput.substring(0, rawOutput.indexOf("?>") + 2) +
                        "<!DOCTYPE xmeml>" +
                        rawOutput.substring(rawOutput.indexOf("?>") + 2)
        );

        try {
            Document validDocument = builder.build(domReader);
            dom.setDocType((DocType) validDocument.getDocType().detach());
        } catch (JDOMException e) {
            throw new MalformedDocumentException("JDOMException", getClass(), e);
        } catch (IOException e) {
            throw new MalformedDocumentException("IOException", getClass(), e);
        }
    }
}
